package com.jinbaoty.recyclebins.activity;

import androidx.annotation.NonNull;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.StringUtils;
import com.camerakit.CameraKitView;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.jinbaoty.recyclebins.MyApplication;
import com.jinbaoty.recyclebins.command.CommandOrder;
import com.jinbaoty.recyclebins.command.CommandParam;
import com.jinbaoty.recyclebins.command.CommandTask;
import com.jinbaoty.recyclebins.netstate.NetStateChangeObserver;
import com.jinbaoty.recyclebins.netstate.NetStateChangeReceiver;
import com.jinbaoty.recyclebins.netstate.NetworkType;
import com.jinbaoty.recyclebins.server.DefaultCallback;
import com.jinbaoty.recyclebins.server.Items;
import com.jinbaoty.recyclebins.server.User;
import com.jinbaoty.recyclebins.server.UserInfo;
import com.jinbaoty.recyclebins.server.download.AndroidDownloadManager;
import com.jinbaoty.recyclebins.server.download.AndroidDownloadManagerListener;
import com.jinbaoty.recyclebins.utils.DataHelper;
import com.jinbaoty.recyclebins.utils.GlideImageLoader;
import com.jinbaoty.recyclebins.R;
import com.jinbaoty.recyclebins.command.ScanTask;
import com.jinbaoty.recyclebins.server.APIService;
import com.jinbaoty.recyclebins.server.OrderForm;
import com.jinbaoty.recyclebins.server.ResponseData;
import com.jinbaoty.recyclebins.server.update.CustomUpdatePrompter;
import com.jinbaoty.recyclebins.server.vo.CommandFromService;
import com.jinbaoty.recyclebins.command.UsbPortUtils;
import com.jinbaoty.recyclebins.utils.HexDump;

import com.jinbaoty.recyclebins.utils.Utils;
import com.jinbaoty.recyclebins.utils.ZXingUtils;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.util.TextInfo;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.orhanobut.logger.Logger;
import com.otaliastudios.cameraview.CameraView;
import com.sdsmdg.tastytoast.TastyToast;
import com.squareup.picasso.Picasso;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.xuexiang.xui.widget.dialog.DialogLoader;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.utils.UpdateUtils;
import com.youth.banner.Banner;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.bingoogolapple.qrcode.zxing.ZXingView;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.view.View.*;
import static com.jinbaoty.recyclebins.utils.Utils.keyCodeToChar;

public class MainActivity extends BaseActivity   implements NetStateChangeObserver, AMapLocationListener {

    private static final String TAG="MainActivity";

    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    private static final int REG_FACE_CODE = 0x1000;

    private static final int REG_STATUS_REGED = 1;//已注册；
    private static final int REG_STATUS_REGING = 2;//正在注册；
    private static final int REG_STATUS_CANCEL = 3;//取消注册；

    private static final int LOGIN_FACE = 10;//人脸识别
    private static final int LOGIN_QRCODE = 11;//扫码
    private static final int LOGIN_CARD = 12;//刷卡

    private int loginMethod = 0;

    private  int orderIndex;
    private byte[] faceData;//人脸图片数据
    private byte[] featureData;//人脸特征数据
    private String faceLocalId;//人脸本地照片id；
    /**
     * 存放注册图的目录
     */
    public static final String SAVE_IMG_DIR = "register" + File.separator + "imgs";

    MaterialDialog weightDialog;
    // 在线激活所需的权限
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    private DbManager.DaoConfig daoConfig;
    public DbManager.DaoConfig getDaoConfig() {
        return daoConfig;
    }
    private DbManager dbManager;

    @ViewInject(R.id.banner)
    private Banner banner;
/*
    @ViewInject(R.id.zxingview)
    private ZXingView zXingView;*/

    @ViewInject(R.id.cardNoBtn)
    private ImageButton cardNoBtn;

    @ViewInject(R.id.qrcodeBtn)
    private ImageButton qrcodeBtn;

    @ViewInject(R.id.quickBtn)
    private ImageButton quickBtn;

    private MaterialDialog qrcodeDialog;

    private ImageView qrcodeImageView;

    private MaterialDialog cardDialog;
    private MaterialDialog codeDialog;
    private EditText cardNoEditText;

    private Handler serialStatusHandler;
    public static final int WEIGHT_RETURN = 0x7d;
    private static final String ACTION_USB_PERMISSION = "com.jinbaoty.recyclebins.USB_PERMISSION";

    private BroadcastReceiver mUsbPermissionActionReceiver;

    private UsbSerialPort port;

    //private CommandTask serialPortTask;

    private MaterialDialog msgDialog;

    @ViewInject(R.id.binsTypeView)
    private GridView binsTypeGridView;

    @ViewInject(R.id.binsTypeTextView)
    private TextView binsTypeTextView;

    @ViewInject(R.id.wasteTypeView)
    private ImageView wasteTypeImageView;

    List<Map<String,Object>> wasteDataList = new ArrayList<>();

    private CommonAdapter<Map<String, Object>> wasteAdapter = null;

    private int binsType=0;

    List<Map<String,Object>> binsDataList = new ArrayList<>();

    private CommonAdapter<Map<String,Object>> binsTypeAdapter = null;

    private ViewHolder preBinTypeView;

    private int prePosition=0;


    private MaterialDialog adminDialog;


    private MaterialDialog jzDialog;
    private ScanTask scanTask;

    private MaterialDialog cameraDialog;

    private CameraView cameraView;

    private final int RECY_TYPE_CARD = 0x100;
    private final int RECY_TYPE_QRCODE = 0x101;
    private final int RECY_TYPE_PUBLIC_GOOD = 0x102;

    private Bitmap photoBitmap;

    private MaterialDialog loadingDialog;


    @ViewInject(R.id.closeDoor)
    private TextView closeDoor;
    @ViewInject(R.id.titlebar)
    private CommonTitleBar titleBar;
    @ViewInject(R.id.videoplayer)
    private VideoView videoView;
    @ViewInject(R.id.videoContainer)
    private LinearLayout videoContainer;

    private CameraKitView cameraKitView;

    private int cameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;

    boolean libraryExists = true;
    // Demo 所需的动态库文件
    private static final String[] LIBRARIES = new String[]{
            // 人脸相关
            "libarcsoft_face_engine.so",
            "libarcsoft_face.so",
            // 图像库相关
            "libarcsoft_image_util.so",
    };

    FaceActiceReceiver faceActiceReceiver;

    @ViewInject(R.id.faceCheck)
    private ImageButton faceCheckBtn;

    private boolean isFaceServiceActive = false;

    private  MaterialDialog msg;
    //声明mlocationClient对象
    AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    AMapLocationClientOption mLocationOption = null;


    private String bindType = "qrcode";//人脸绑定类型：{"card"："刷卡绑定","qrcode":"二维码绑定"}


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //updateApp();
        x.view().inject(this);
        initDb();
        initView();
        //this.registerReceiver(new UpdateReceiver(),new IntentFilter());
        faceActiceReceiver = new FaceActiceReceiver();
        this.registerReceiver(faceActiceReceiver,new IntentFilter("com.arcsoft.arcsoftdemo.faceactive"));
        NetStateChangeReceiver.registerReceiver(this);
    }
    private void initDb(){
        try {
            dbManager = x.getDb(MyApplication.daoConfig);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
   /* private void updateApp(){
        XUpdate
                .newBuild(this).updateUrl(APIService.SERVER_URL+"/app/updateInfo")
                .updatePrompter(new CustomUpdatePrompter(this))
                .update();
    }*/
    private void initView(){
        {//初始化高德地图定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            getLocationInfo();
        }
        MediaController controller = new MediaController(this);
        videoView.setMediaController(controller);

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
                mp.start();
                mp.setLooping(true);
            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Logger.d("视频结束");
            }
        });
        loadingDialog = new MaterialDialog.Builder(this)
                .limitIconToDefaultSize()
                .title("提示")
                .content("数据加载中，请稍后。。。")
                .progress(true, 0)
                .progressIndeterminateStyle(false)
                .build();
        //cameraKitView = findViewById(R.id.cameraKitView);
        /*View cameraLayout = inflate(this, R.layout.camera_layout, null);
        cameraDialog = new MaterialDialog.Builder(this).customView(cameraLayout,true).build();
        cameraView = cameraLayout.findViewById(R.id.camera);
        cameraView.setLifecycleOwner(this);
        cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                result.toBitmap(new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {

                    }
                });
            }
        });*/
        final View jzDialogView = inflate(this, R.layout.jz_dialog, null);
        jzDialog = new MaterialDialog.Builder(this).title("称重校准")
                .inputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL)
                .input("请输入校准重量", "", false, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence cardNo) {

                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        SharedPreferences appConfig = getAppConfig();
                        CommandParam[] commandParamOrders = CommandOrder.orderSet[orderIndex];
                        Double preWeight;
                        try {
                            int write = port.write(new byte[]{commandParamOrders[4].getCommandVal()}, 400);
                            byte buffer[] = startReadData(commandParamOrders[4]);
                            int readLen = buffer.length;
                            String weightStr  = new String(buffer,0,readLen);
                            Logger.d("回收返回："+weightStr);
                            weightStr = weightStr.replaceAll("[^0-9.]", "");
                            if(NumberUtil.isDouble(weightStr)) {
                                preWeight = Double.parseDouble(weightStr);

                                SharedPreferences.Editor edit = appConfig.edit();
                                edit.putString("weight"+orderIndex,NumberUtil.roundStr(Double.valueOf(dialog.getInputEditText().getText().toString())/preWeight,3) +"");
                                edit.commit();
                                Logger.d("weight"+orderIndex+":"+Double.valueOf(dialog.getInputEditText().getText().toString())/preWeight+"");

                            }else{

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        dialog.getInputEditText().setText("");
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        msg.dismiss();
                    }
                })
                .alwaysCallInputCallback()
                .build();
      msg =new MaterialDialog.Builder(this).title("通知消息").content("请确定是否强制关门？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        WaitDialog.show(MainActivity.this,"请稍后");
                        CommandParam[][] orderSet = CommandOrder.orderSet;
                        for(int i=0;i<orderSet.length;i++){
                            for(int j=0;j<orderSet[i].length;j++){
                                CommandParam commandParam = orderSet[i][j];
                                if (commandParam.getCommandTag().equals("close")) {
                                    try {
                                        long beginTime = System.currentTimeMillis();
                                        if(port!=null) {
                                            int write = port.write(new byte[]{commandParam.getCommandVal()}, 400);
                                            byte[] buffer = new byte[20];
                                            do {
                                                int readLen = port.read(buffer, commandParam
                                                        .getReadTimeout());
                                                if (readLen > 0) {
                                                    Logger.d(commandParam.getCommandName()+"，返回：" + new String(buffer, 0, readLen));
                                                }
                                            }while(System.currentTimeMillis()-beginTime< commandParam.getReadTimeout());
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        WaitDialog.dismiss();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        msg.dismiss();
                    }
                })
              .canceledOnTouchOutside(false)
                .build();
        closeDoor.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                msg.show();
            }
        });
        msgDialog = createMsgDialog();
        serialStatusHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                serialStatusChange(msg);
            }
        };
        //APIService.forceInit(this);
        //List<String> imageList = Arrays.asList(APIService.SERVER_URL+"upload/img/waste2.jpg",APIService.SERVER_URL+"upload/img/waste3.jpg");
        banner.setImageLoader(new GlideImageLoader());


/*
        adminDialog = new MaterialDialog.Builder(this).title("管理员模式")
                .inputType(InputType.TYPE_CLASS_PHONE|InputType.TYPE_TEXT_VARIATION_PASSWORD)
                        .input("请输入密码",  "", false,new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                adminManage(dialog,input);
                            }
                        })
                        .alwaysCallInputCallback()
                        .build();*/




     /*   titleBar.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                return false;
            }
        });*/

        binsTypeAdapter = new CommonAdapter<Map<String,Object>>(this,R.layout.bins_type_view,binsDataList){

            @Override
            protected void convert(ViewHolder viewHolder, Map<String, Object> item, int position) {
                viewHolder.setText(R.id.textView,item.get("typeName").toString());
                Boolean selected = (Boolean)item.get("selected");
                viewHolder.setBackgroundRes(R.id.textView,selected?R.drawable.bins_type_border:R.drawable.bins_type_border2);
                SharedPreferences appConfig = getAppConfig();
                String weight = appConfig.getString("weight"+position, "");
                if(selected){
                    binsTypeTextView.setText("您选择回收的是："+binsDataList.get(position).get("typeName"));
                    if(weight!=null&&weight!=""){
                        CommandTask.jzNumber=Double.valueOf(weight);
                        Logger.d("校准:"+weight);
                    }

                }
                final Object icon = item.get("img");
                if(icon!=null && ObjectUtil.length(icon)>0){
                    //Logger.d("icon: "+icon.toString());
                    ImageView view = viewHolder.getView(R.id.imageView);
                    Picasso.get().load(icon.toString()).into(view);

                }else {
                    viewHolder.setImageResource(R.id.imageView, R.drawable.ping);
                }
                item.put("textView",viewHolder);
            }
        };


        binsTypeGridView.setAdapter(binsTypeAdapter);
        binsTypeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SneakyThrows
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                binsType = position;
                binsTypeTextView.setText("您选择回收的是："+binsDataList.get(position).get("typeName"));
                wasteInfoChangeFor(position,view);
                binsDataList.get(prePosition).put("selected",false);
                binsDataList.get(position).put("selected",true);

                prePosition = position;
                binsTypeAdapter.notifyDataSetChanged();


            }

        });


        binsTypeGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                jzDialog.show();
                orderIndex=position;
                return true;
            }
        });
        wasteAdapter =
        new CommonAdapter<Map<String,Object>>(this,R.layout.waste_view,wasteDataList){

            @Override
            protected void convert(ViewHolder viewHolder, Map<String, Object> item, int position) {
                viewHolder.setText(R.id.wasteNameTextView,item.get("wasteName").toString());
                final Object icon = item.get("img");
                if(icon!=null && ObjectUtil.length(icon)>0){
                    ImageView view = viewHolder.getView(R.id.wasteIconImageView);
                    Picasso.get().load(icon.toString()).into(view);
                }else {
                    viewHolder.setImageResource(R.id.wasteIconImageView, R.drawable.ping);
                }
            }
        };

        //wasteInfoGridView.setAdapter(wasteAdapter);

        //initWasteTypeData();

        View qrcodeDialogView = inflate(this, R.layout.qrcode_dialog, null);


        qrcodeDialog = new MaterialDialog.Builder(this).customView(R.layout.qrcode_dialog,true).dismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(scanTask!=null){
                    scanTask.setCancle(true);
                    scanTask = null;
                }
            }
        }).title("扫码回收").build();//new AlertDialog.Builder(this).setTitle("扫码回收").setView(qrcodeDialogView).create();

        qrcodeImageView = (ImageView) qrcodeDialog.findViewById(R.id.qrcodeImageView);

        final View codeDialogView = inflate(this, R.layout.card_dialog, null);
        codeDialog = new MaterialDialog.Builder(this).title("刷卡回收")
                .inputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .positiveText("确认")
                .input("请扫码", "", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {

                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Map<String,String> paramMap =new HashMap<>();
                        String cardno=dialog.getInputEditText().getText().toString();
                        paramMap.put("qrcode",cardno+"");
                        APIService.cardNoSearch(paramMap, new DefaultCallback() {
                            public void response(String response, int code) {
                                final ResponseData responseData = this.getResponseData(response);
                                if(responseData.getCode()==200){

                                    com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)responseData.getData();
                                    User userInfo = new User();
                                    userInfo.setUser_id(jsonObject.getString("user_id"));

                                    recycleByCard(cardno,userInfo);
                                }else {
                                    //alert("身份验证信息", "您尚未关注公众号或小程序，请先关注再进行回收操作");

                                    showTip("卡号尚未注册，请先注册卡号！");
                                }
                            }
                        });

                        dialog.dismiss();
                        dialog.getInputEditText().setText("");
                    }
                })
                .alwaysCallInputCallback()
                .build();
        final View cardDialogView = inflate(this, R.layout.card_dialog, null);


        cardDialog = new MaterialDialog.Builder(this).title("刷卡回收")
                .inputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .input("请刷卡或输入卡号", "", false, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence cardNo) {
                        if(StrUtil.length(cardNo)==10){
                            Map<String,String> paramMap =new HashMap<>();
                            paramMap.put("qrcode",cardNo+"");
                            APIService.cardNoSearch(paramMap, new DefaultCallback() {
                                public void response(String response, int code) {
                                    final ResponseData responseData = this.getResponseData(response);
                                    if(responseData.getCode()==200){

                                        com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)responseData.getData();
                                        User userInfo = new User();
                                        userInfo.setUser_id(jsonObject.getString("user_id"));

                                        recycleByCard(cardNo.toString(),userInfo);
                                    }else {
                                        //alert("身份验证信息", "您尚未关注公众号或小程序，请先关注再进行回收操作");

                                        showTip("卡号尚未注册，请先注册卡号！");
                                    }
                                }
                            });

                            dialog.dismiss();
                            dialog.getInputEditText().setText("");
                        }
                    }
                })
                .inputRange(10,10)
                .alwaysCallInputCallback()
                .build();
        int cameraType = MyApplication.getCameraType();
        if(cameraType==-1){
            //takePhoto();
            UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
            Set<String> deviceKeys = deviceList.keySet();
            for (String deviceKey : deviceKeys) {
                UsbDevice usbDevice = deviceList.get(deviceKey);
                if(usbDevice==null) continue;
                String manufacturerName = usbDevice.getManufacturerName();
                if (manufacturerName!=null && manufacturerName.equalsIgnoreCase("TJ-2053-190702")) {
                    String productName = usbDevice.getProductName();
                    if (productName!=null && productName.indexOf("caise")>=0) {
                        cameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;
                    }else{
                        cameraType = Camera.CameraInfo.CAMERA_FACING_BACK;
                    }
                    final SharedPreferences deviceInfoConfig = this.getSharedPreferences("device_info", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = deviceInfoConfig.edit();
                    edit.putInt("camera_type",cameraType);
                    edit.commit();
                    break;
                }
            }
        }
        DialogSettings.tipTheme = DialogSettings.THEME.LIGHT;
        DialogSettings.theme = DialogSettings.THEME.LIGHT;
        //DialogSettings.contentTextInfo = new TextInfo().setFontColor(Color.parseColor("#cccccc"));
        DialogSettings.tipTextInfo  = new TextInfo().setFontColor(Color.parseColor("#666666")).setFontSize(18);
        DialogSettings.init();
        initUseSerialPort();
        loadDeviceData();
        //timerWeight();

    }

    private void loadDeviceData(){
        final SharedPreferences appConfig = getAppConfig();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {


                final String deviceId = APIService.getDeviceId(MainActivity.this);

                if(deviceId.isEmpty()) {
                    APIService.init(MainActivity.this);

                }else{


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadFromLocal();//加载本地存储数据
                            loadDataFormServer();//加载服务器数据
                        }
                    });

                    this.cancel();
                }
            }
        },0,2000);

    }

    private void loadFromLocal(){
        SharedPreferences appConfig = getAppConfig();
        String imgPathListStr = appConfig.getString("imgPathList", "");
        List<String> imgPathList = StrSpliter.splitTrim(imgPathListStr, ";", true);
        initBanner(imgPathList);


        LinearLayout leftCustomView = (LinearLayout)titleBar.getLeftCustomView();
        TextView phoneTextView = (TextView)leftCustomView.getChildAt(0);
        String servicePhone = appConfig.getString("service_phone","");
        phoneTextView.setText("客服电话："+ servicePhone);
       // LinearLayout centerCustomView=(LinearLayout)titleBar.getCenterCustomView();



        TextView binsNoTextView = (TextView)leftCustomView.getChildAt(0);

        String binsNo = appConfig.getString("SIGN_APPID", "");
        binsNoTextView.setText("回收箱编号："+binsNo);







    }
    private void loadDataFormServer(){
        APIService.serviceInfo(new StringCallback() {//获取客服信息
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                SharedPreferences appConfig = getAppConfig();
                ResponseData responseData = JSON.parseObject(response,ResponseData.class);
                Object data = responseData.getData();
                com.alibaba.fastjson.JSONObject serviceInfo = (com.alibaba.fastjson.JSONObject) data;
                LinearLayout leftCustomView = (LinearLayout)titleBar.getLeftCustomView();

                TextView phoneTextView = (TextView)leftCustomView.getChildAt(0);
                String servicePhone = serviceInfo.getString("phone");
                phoneTextView.setText("客服电话："+ servicePhone);
                if(!StringUtils.isEmpty(servicePhone)) {
                    SharedPreferences.Editor edit = appConfig.edit();
                    edit.putString("service_phone", servicePhone);
                    edit.commit();
                }

                TextView binsNoTextView = (TextView)leftCustomView.getChildAt(1);

                String binsNo = appConfig.getString("SIGN_APPID", "");
                binsNoTextView.setText("回收箱编号："+binsNo);



            }
        });

        APIService.bannerList(new StringCallback() {//获取广告
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Logger.d("广告返回："+response);
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray data = jsonObject.getJSONArray("data");
                    if(data!=null) {
                        String imgPathList = "";
                        int length = data.length();
                        List<String> imgPathStrList = new ArrayList<>();
                        for(int i=0;i<length;i++){
                            imgPathStrList.add(data.getString(i));
                            imgPathList+=data.getString(i)+",";
                        }
                        initBanner(imgPathStrList);
                        SharedPreferences appConfig = getAppConfig();
                        SharedPreferences.Editor edit = appConfig.edit();
                        edit.putString("imgPathList", imgPathList);
                        edit.commit();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        initWasteTypeData();
    }

    private void initBanner(List<String> imgPathList){
        List<String> imgList = new ArrayList<>();
        boolean isVideo = false;
        int length = imgPathList.size();
        for(int i=0;i<length;i++){
            String imgWebPath = imgPathList.get(i);
            if(StrUtil.endWithAny(imgWebPath.toLowerCase(),".jpg",".bmp",".gif",".svg",".png")) {
                imgList.add( imgWebPath);

            }else{
                if(StrUtil.endWith(imgWebPath.toLowerCase(),".mp4")) {
                    isVideo = true;
                    String uri = imgWebPath;//("android.resource://" + getPackageName() + "/" + R.raw.fangyuanyufu);
                    File externalFilesDir = MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                    File tarFile = new File(externalFilesDir, FileUtil.getName(imgWebPath));
                    if(tarFile.exists()){
                        uri = tarFile.getAbsolutePath();
                    }else{
                        new AndroidDownloadManager(MainActivity.this, uri,externalFilesDir.getAbsolutePath(),tarFile.getName())
                                .setListener(new AndroidDownloadManagerListener() {
                                    @Override
                                    public void onPrepare() {
                                        Log.d(TAG, "onPrepare");
                                    }

                                    @Override
                                    public void onSuccess(String path) {
                                        Log.d(TAG, "onSuccess >>>>" + path);
                                    }

                                    @Override
                                    public void onFailed(Throwable throwable) {
                                        Log.e(TAG, "onFailed", throwable);
                                    }
                                })
                                .download();
                    }
                    Logger.d("视频路径："+uri);
                    videoContainer.setVisibility(VISIBLE);
                    banner.setVisibility(GONE);
                    videoView.setVideoURI(Uri.parse(uri));
                    videoView.start();
                    break;
                }
            }

        }
        if(!isVideo) {
            banner.setVisibility(VISIBLE);
            videoContainer.setVisibility(GONE);
            banner.setImages(imgList);
            banner.start();
        }
    }
    private void initUseSerialPort(){
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
        if (availableDrivers.isEmpty()) {
            new MaterialDialog.Builder(this).title("初始化失败").content("请连接usb串口线").show();
            return;
        }else{
            Logger.d("usb串口初始化，共找到%s个usb串口设备",availableDrivers.size());
            mUsbPermissionActionReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (ACTION_USB_PERMISSION.equals(action)) {
                        context.unregisterReceiver(this);//解注册
                        synchronized (this) {
                            UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                                if(null != usbDevice){
                                    Log.e("串口权限",usbDevice.getDeviceName()+"已获取USB权限");
                                }
                            }
                            else {
                                //user choose NO for your previously popup window asking for grant perssion for this usb device
                                Log.e("串口权限",String.valueOf("USB权限已被拒绝，Permission denied for device" + usbDevice));
                            }
                        }

                    }
                }
            };
            // Open a connection to the first available driver.
            UsbSerialDriver driver = availableDrivers.get(0);
            UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
            if (connection == null) {
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

                if(mUsbPermissionActionReceiver != null) {
                    registerReceiver(mUsbPermissionActionReceiver, filter);
                }

                PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
                manager.requestPermission(driver.getDevice(),mPermissionIntent);
                return;
            }

            openPort(manager,driver);
            //开始扫描订单

        }
    }
    public void openPort(UsbManager manager,UsbSerialDriver driver){
        UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
        this.port = driver.getPorts().get(0); // Most devices have just one port (port 0)
        try {
            this.port.open(connection);
            this.port.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            //serialPortTask = new CommandTask(this.port, serialStatusHandler);
            //new SerialInputOutputManager(this.port, serialPortTask);
            try {
                this.port.setDTR(true);
            }catch (IOException x){
                x.printStackTrace();
            }
            try {
                this.port.setRTS(true);
            }catch (IOException x){
                x.printStackTrace();
            }
            ResponseData responseData = new UsbPortUtils(this.port).sendForResult(CommandOrder.DOOR1_WEIGHT);
            if(responseData.getSuccess()==false){
                TipDialog.showWait(this,"串口通信失败！");
            }
            //new Thread(new ScanTask(this.port,serialStatusHandler)).start();
            //startScanOrder();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //初始化垃圾分类
    public void initWasteTypeData(){
        APIService.wasteTypeList(new StringCallback(){

            @Override
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
            }

            @SneakyThrows
            @Override
            public void onResponse(String response, int id) {
                ResponseData responseData = JSON.parseObject(response, ResponseData.class);
                Log.d("垃圾类别",""+responseData);
                com.alibaba.fastjson.JSONArray dataList = (com.alibaba.fastjson.JSONArray)responseData.getData();
                List<Map<String,Object>> typeList = new ArrayList<>();
                for(int i=0;i<dataList.size();i++) {
                    com.alibaba.fastjson.JSONObject data = (com.alibaba.fastjson.JSONObject)dataList.get(i);
                    Map<String,Object> dataMap = new HashMap<>();
                    String typeName = data.getString("typeName");
                    dataMap.put("typeName",typeName);
                    Log.d("垃圾类别",typeName);
                    Integer commandSet = data.getInteger("commandSet");
                    dataMap.put("commandSet",commandSet);
                    String credit = data.getString("credit");
                    dataMap.put("credit",credit);
                    String image = data.getString("image");
                    dataMap.put("image",image);
                    Long wasteTypeId = data.getLong("id");
                    dataMap.put("id",wasteTypeId);

                    String icon = data.getString("icon");
                    if(StrUtil.isNotBlank(icon)){
                        dataMap.put("img",icon);
                    }else {
                        dataMap.put("img", R.drawable.ping);
                    }
                    try {
                        dataMap.put("wasteList", data.getJSONArray("wasteInfoList"));
                    }catch (Exception e){

                    }
                    dataMap.put("selected",i==0?true:false);
                    typeList.add(dataMap);
                }
                binsDataList.clear();
                binsDataList.addAll(typeList);
                binsTypeAdapter.notifyDataSetChanged();


                wasteInfoChangeFor(0,null);


            }
        });
    }
    //初始化小分类
    private void wasteInfoChangeFor(int index,View convertView) throws IOException {
        wasteDataList.clear();
        Map<String, Object> typeImage = binsDataList.get(index);
        String wasteImage = (String) typeImage.get("image");

        Picasso.get().load(wasteImage).into(wasteTypeImageView);

       // wasteTypeImageView.setImageBitmap(bitmap);



    }

    //人脸识别
    @Event(value=R.id.faceCheck)
    private void faceCheckClick(View view){
        DialogLoader.getInstance().showTipDialog(MainActivity.this,"提示 ","暂未开通敬请期待","").show();

       /* if(isFaceServiceActive) {
            msgDialog.hide();
            //checkLibraryAndJump(RegisterAndRecognizeActivity.class);
            //checkLibraryAndJump(RegisterAndRecognizeActivity.class);
            this.loginMethod = LOGIN_FACE;
            Intent intent = new Intent();
            final SharedPreferences deviceInfoConfig = this.getSharedPreferences("device_info", Context.MODE_PRIVATE);
            int camera_type = deviceInfoConfig.getInt("camera_type", Camera.CameraInfo.CAMERA_FACING_FRONT);
            this.cameraType = camera_type;
            Logger.d("人脸识别摄像头：" + (this.cameraType == Camera.CameraInfo.CAMERA_FACING_BACK ? "back" : "front"));
            intent.putExtra("cameraType", camera_type);
            intent.putExtra("deviceId",APIService.getDeviceId(this));
            intent.setAction("com.arcsoft.arcface.registeractivity");
            startActivityForResult(intent, REG_FACE_CODE);
        }else{
            //msgDialog.setContent("人脸识别正在激活请稍后");
            //msgDialog.show();
            WaitDialog.show(this,"人脸识别激活中请稍后再试。。。");
        }*/
    }

    //二维码回收
    @Event(value=R.id.qrcodeBtn)
    private void qrcodeBtnClick(View view){
        //qrcodeDialog.setTitle("扫码回收");
      //  takePhoto(RECY_TYPE_QRCODE);
        this.loginMethod=LOGIN_QRCODE;
        codeDialog.setTitle("扫码投递");
        codeDialog.show();
    }

    //刷卡回收
    @Event(value=R.id.cardNoBtn)
    private void cardNoBtnClick(View view){
        this.loginMethod=LOGIN_CARD;
        cardDialog.setTitle("刷卡投递");
        cardDialog.show();
        //takePhoto(RECY_TYPE_CARD);
    }

    //紧急按钮
    @Event(value=R.id.quickBtn)
    private void quickBtnClick(View view){

    }


    private void recycleByCard(String cardNo,User user){
       /* final Toast toast = TastyToast.makeText(MainActivity.this, "\n正在验证您的卡号\n", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();*/


        Map<String,String> paramMap =new HashMap<>();
        Map<String, Object> binsTypeMap = binsDataList.get(binsType);
        Long wasteTypeId = (Long) binsTypeMap.get("id");

        paramMap.put("wasteTypeId",wasteTypeId+"");
        paramMap.put("cardNo",cardNo.toString());

        OrderForm orderFormObj = new OrderForm();
        orderFormObj.setUserId(Long.parseLong(user.getUser_id()));
        orderFormObj.setWasteWeight(0l);
        orderFormObj.setFinishTime(new Date());
        orderFormObj.setWasteId((Long) binsDataList.get(binsType).get("id"));
        orderFormObj.setCommandSet((Integer) binsDataList.get(binsType).get("commandSet"));
       // orderFormObj.getBinsId(Build.ID.toString());


       //orderFormObj.setErrorMsg("二维码注册人脸失败");
        //Message stopMessage = new Message();
   //     stopMessage.what = CommandParam.WAITING_TAG;
        this.scanTask = new ScanTask(port, serialStatusHandler);
        new Thread(scanTask).start();
        this.scanTask.setOrderForm(orderFormObj);

        //CommandTask task=new CommandTask(port,serialStatusHandler);
      //  task.startRecycleTask(orderFormObj);


        /*this.scanTask.run();
        this.scanTask.setTaskRunning(false);*/
      //  stopMessage.obj = task;
      //  serialStatusHandler.sendMessage(stopMessage);
        //loadingDialog.show();
        startScanOrder();
      /*  APIService.createOrderWithPhoto(paramMap, photoBitmap,new Callback(){

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                toast.cancel();
                String resultStr = response.body().string();
                ResponseData responseData = JSON.parseObject(resultStr, ResponseData.class);
                Looper.prepare();
                if(!responseData.getSuccess()){
                    DialogLoader.getInstance().showTipDialog(MainActivity.this,"提示 ",responseData.getMessage(),"").show();
                }else{

                }
                loadingDialog.dismiss();
                Looper.loop();
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

        });*/
    }





    //回收状态变更
    public void serialStatusChange(Message message){
        if(message.what==ScanTask.ORDER_CREATE){
            //Logger.d("扫描到的订单："+message.obj);
            //if(qrcodeDialog!=null) qrcodeDialog.dismiss();
            OrderForm orderForm = (OrderForm) message.obj;
           // com.alibaba.fastjson.JSONObject orderForm = (com.alibaba.fastjson.JSONObject) responseData.getData();
           // long orderId = orderForm.getLong("id");
           /* if(this.loginMethod==LOGIN_FACE){//二维码绑定
              *//*  UserInfo existUser = null;
                try {
                    com.alibaba.fastjson.JSONObject userIdModel = orderForm.getJSONObject("userIdModel");
                    String cardNo = userIdModel.getString("cardNo");
                    String userId = orderForm.getString("userId");
                    existUser = dbManager.selector(UserInfo.class).where("card_no", "=", cardNo).findFirst();
                    if (existUser!=null) {
                        if(!existUser.getUserId().equals(userId)) {
                            showTip("您的微信已被绑定了另一个用户！");
                            OrderForm orderFormObj = com.alibaba.fastjson.JSONObject.parseObject(orderForm.toJSONString(), OrderForm.class);
                            orderFormObj.setState(new Long(CommandTask.STOP));
                            orderFormObj.setWasteWeight(0l);
                            orderFormObj.setFinishTime(new Date());
                            orderFormObj.setErrorMsg("二维码注册人脸失败");
                            Message stopMessage = new Message();
                            stopMessage.what = CommandTask.FINISH;
                            stopMessage.obj = orderFormObj;
                            serialStatusHandler.sendMessage(stopMessage);
                            return;
                        }
                    }else{
                        UserInfo userInfo = UserInfo.builder().userId(userId).cardNo(cardNo).userName(orderForm.getString("userName")).userNo(userIdModel.getString("userNo")).photoName(faceLocalId).build();
                        try {
                            dbManager.save(userInfo);
                            showTip("绑定成功！");
                            *//**//*qrcodeDialog.dismiss();
                            qrcodeDialog.setTitle("扫码回收");*//**//*
                            this.loginMethod = LOGIN_CARD;
                            *//**//*APIService.regFace(featureData, cardNo, new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {

                                }

                                @Override
                                public void onResponse(String response, int id) {

                                }
                            });*//**//*
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }*//*

            }*/
            Long wasteId = orderForm.getWasteId();
            if(wasteId==null) {
                Long wasteTypeId = (Long) binsDataList.get(binsType).get("id");
                if(wasteTypeId==null){
                    Logger.d("binsDataList:"+binsDataList);
                }
                /*loadingDialog.show();
                APIService.updateOrder(wasteTypeId, orderId, photoBitmap, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        loadingDialog.dismiss();
                    }
                });*/
                msgDialog.setCancelable(false);
            }

        }else if(message.what== CommandParam.WAITING_TAG){
            final CommandTask task = (CommandTask)message.obj;
            CommandParam nowCommand = task.getNowCommand();
            weightDialog=new MaterialDialog.Builder(this).title("投递消息").content("请将回收物放入回收箱，投放完毕，点击'结束投递'")
                    .positiveText(nowCommand.getSuccessMsg())
                    .negativeText(nowCommand.getErrorMsg())
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            task.setWaiting(CommandParam.WAITING_OK);
                        }
                    })
                    .canceledOnTouchOutside(false)
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            task.setWaiting(CommandParam.WAITING_END);
                        }
                    })
                    .show();
        }else if(message.what==CommandTask.FINISH) {
            msgDialog.setCancelable(true);
            this.loginMethod=0;
            OrderForm orderForm = (OrderForm)message.obj;


            if(new Long(CommandTask.STOP).equals(orderForm.getState())){
                msgDialog.dismiss();
                if(qrcodeDialog!=null)qrcodeDialog.dismiss();
            }else {
                Items items=new Items();
                items.setGoods_id(orderForm.getWasteId());

                items.setCount(Double.parseDouble(orderForm.getWasteWeight().toString())/1000);
                com.alibaba.fastjson.JSONObject jsonResult = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(items);
                Map<String,String> paramMap =new HashMap<>();
                paramMap.put("user_id",orderForm.getUserId()+"");
                paramMap.put("items","["+jsonResult.toJSONString()+"]");

                paramMap.put("weight",(Double.parseDouble(orderForm.getTotalPrice().toString())/1000)+"");

                Logger.d("初始重量："+Double.parseDouble(orderForm.getTotalPrice().toString())/1000+"");

                //  paramMap.put("state",orderForm.getState()+"");
                // paramMap.put("errorMsg",orderForm.getErrorMsg());
                APIService.createOrderWithPhoto(paramMap, photoBitmap, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Logger.d("结束错误："+e.getMessage());
                        Message msg= new Message();
                        msg.obj = e.getMessage();
                        serialStatusHandler.sendMessage(msg);
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        //
                        String resultStr = response.body().string();
                        ResponseData responseData = JSON.parseObject(resultStr, ResponseData.class);

                        Looper.prepare();
                        if(!responseData.getSuccess()){
                            Message msg= new Message();
                            msg.obj = responseData.getMessage();
                            serialStatusHandler.sendMessage(msg);
                        }else{
                            Message msg= new Message();
                            msg.obj = responseData.getMessage();
                            serialStatusHandler.sendMessage(msg);

                        }
                        Logger.d("结束成功："+response);
                    }
                });
            }

        }else if(message.what==WEIGHT_RETURN){

            if (weightDialog == null) weightDialog = createMsgDialog();
            if(ObjectUtil.length(message.obj)>0) {
                weightDialog.setContent(message.obj.toString());

            }
        }else{
            this.loginMethod=0;
            if (msgDialog == null) msgDialog = createMsgDialog();
            if(ObjectUtil.length(message.obj)>0) {
                msgDialog.setContent(message.obj.toString());
                if (!msgDialog.isShowing()) {
                    msgDialog.show();
                    //Log.d("串口消息窗口", "显示");
                }
            }
        }
    }




    private MaterialDialog createMsgDialog(){
        msgDialog= new MaterialDialog.Builder(this).title("智能回收箱运行中").cancelable(false).positiveText("确定").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which){
                dialog.dismiss();
            }
        }).build();

        return msgDialog;
    };
    @Override
    protected void onPause() {
        super.onPause();
        if (msgDialog != null && msgDialog.isShowing()) {
            msgDialog.dismiss();
            msgDialog = null;
            Log.d("串口消息窗口","dismiss");
        }
        if (cardDialog!= null && cardDialog.isShowing()) {
            cardDialog.dismiss();
            cardDialog = null;
        }
        if(qrcodeDialog!=null && qrcodeDialog.isShowing()){
            qrcodeDialog.dismiss();
            qrcodeDialog = null;
        }
        if(port!=null) {
            try {
                port.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //cameraKitView.onPause();
        NetStateChangeReceiver.unregisterObserver(this);
    }
    public void restartActivity(Activity act){
        Intent intent=new Intent();
        intent.setClass(act, act.getClass());
        act.startActivity(intent);
        act.finish();
    }

    public void adminManage(MaterialDialog dialog,CharSequence input){
        if (input.length() == 9) {
            final Map<String,String> paramMap = new HashMap<>();
            String pwd = "";
            try {
                pwd = Utils.shaEncode(input.toString());
                paramMap.put("pwd", pwd);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SharedPreferences appConfig = this.getAppConfig();
            String secret = appConfig.getString("secret", "");
            if(!StringUtils.isEmpty(secret)){//离线验证密码
                if(StringUtils.equals(pwd,secret)){//验证正确
                    showAdminFunction();
                }else{
                    TipDialog.show(this,"密码不正确,请重新输入！", TipDialog.TYPE.ERROR);
                    EditText inputEditText = adminDialog.getInputEditText();
                    inputEditText.selectAll();
                    inputEditText.requestFocus();
                }
            }else{
                APIService.checkAdminPwd(paramMap, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ResponseData responseData = JSON.parseObject(response, ResponseData.class);
                        if(!responseData.getSuccess()){
                            //new QMUIDialog.MessageDialogBuilder(MainActivity.this).setMessage(responseData.getMessage()).show();
                            DialogLoader.getInstance().showTipDialog(MainActivity.this,"提示 ",responseData.getMessage(),"").show();
                            EditText inputEditText = adminDialog.getInputEditText();
                            inputEditText.selectAll();
                            inputEditText.requestFocus();
                            return;
                        }else{
                            com.alibaba.fastjson.JSONObject binsData = (com.alibaba.fastjson.JSONObject)responseData.getData();
                            Long state = binsData.getLong("state");
                            //if(new Long(3l).equals(state)){//未激活状态，激活成功，保存密码到配置文件
                            SharedPreferences appConfig = getAppConfig();
                            String secret1 = appConfig.getString("secret", "");
                            if(StrUtil.isBlank(secret1)) {
                                SharedPreferences.Editor edit = appConfig.edit();
                                String pwd = paramMap.get("pwd");
                                edit.putString("secret", pwd);
                                edit.commit();
                                APIService.updateSecret(pwd);
                                loadDataFormServer();
                                XToast.success(MainActivity.this, "激活成功！").show();
                                adminDialog.dismiss();
                                return;
                            }
                            //}
                        }
                        showAdminFunction();
                    }
                });
            }

        }

    }

    private void showAdminFunction(){
        Logger.d("进入管理员模式");
        CharSequence[] charSequences = {"设置", "重启", "升级","启动器选择","应用程序列表","初始化", "当前版本号："+ UpdateUtils.getVersionCode(MainActivity.this)};

        new MaterialDialog.Builder(MainActivity.this).title("管理员模式")
                .items("设置", "重启", "升级","启动器选择","应用程序列表","初始化","关闭所有回收箱门","当前版本号："+UpdateUtils.getVersionCode(MainActivity.this))
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                        switch (position) {
                            case 0: {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                startActivity(intent);
                                break;
                            }
                            case 1: {
                                restartActivity(MainActivity.this);
                                break;
                            }
                            case 2: {
                                //updateApp();
                                break;
                            }
                            case 3:{
                                Intent intentw = new Intent(Intent.ACTION_MAIN);
                                intentw.addCategory(Intent.CATEGORY_HOME);
                                intentw.setClassName("android",
                                        "com.android.internal.app.ResolverActivity");
                                startActivity(intentw);
                                break;
                            }
                            case 4:{
                                Intent intent =  new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                                startActivity(intent);
                                break;
                            }
                            case 5:{
                            //   APIService.forceInit(MainActivity.this);
                                restartActivity(MainActivity.this);
                                break;
                            }
                            case 6:{
                                CommandParam[][] orderSet = CommandOrder.orderSet;
                                for(int i=0;i<orderSet.length;i++){
                                    for(int j=0;j<orderSet[i].length;j++){
                                        CommandParam commandParam = orderSet[i][j];
                                        if (commandParam.getCommandTag().equals("close")) {
                                            try {
                                                long beginTime = System.currentTimeMillis();
                                                if(port!=null) {
                                                    int write = port.write(new byte[]{commandParam.getCommandVal()}, 400);
                                                    byte[] buffer = new byte[20];
                                                    do {
                                                        int readLen = port.read(buffer, commandParam
                                                                .getReadTimeout());
                                                        if (readLen > 0) {
                                                            Logger.d(commandParam.getCommandName()+"，返回：" + new String(buffer, 0, readLen));
                                                        }
                                                    }while(System.currentTimeMillis()-beginTime< commandParam.getReadTimeout());
                                                }
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
                .show();
    }
    private void startScanOrder(){
        if(this.scanTask==null || !this.scanTask.isTaskRunning()) {
            this.scanTask = new ScanTask(port, serialStatusHandler);
            new Thread(scanTask).start();
            Logger.d("启动新的扫描线程：%s",this.scanTask);
        }else{
            Logger.d("已有扫描线程在运行：%s",this.scanTask);
        }
    }

    private void  takePhoto(final int requestCode){
        if(this.port==null){
            TipDialog.show(this,"串口未连接！请联系管理员！", TipDialog.TYPE.WARNING);
            return;
        }
        final Context context = this;
        //if(requestCode==RECY_TYPE_PUBLIC_GOOD){
        DialogLoader.getInstance().showConfirmDialog(context, "出于安全考虑，将跳转采集您的照片确认身份信息。",
                "确认进入", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MainActivity.this, CameraActivity.class);//new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        final SharedPreferences deviceInfoConfig = MainActivity.this.getSharedPreferences("device_info", Context.MODE_PRIVATE);
                        int camera_type = deviceInfoConfig.getInt("camera_type", Camera.CameraInfo.CAMERA_FACING_FRONT);
                        MainActivity.this.cameraType = camera_type;
                        intent.putExtra("cameraType", camera_type);
                        startActivityForResult(intent, requestCode);
                        dialog.dismiss();
                    }
                }, "取消本次回收", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DialogLoader.getInstance().showTipDialog(context, "提示", "本次回收结束，感谢您的参与！", "确定").show();
                        dialog.dismiss();
                    }
                }
        );
        //}else {
            /*Logger.d("进入拍照！");
            WaitDialog.show(this,"正在加载中，回收马上开始。。。").setTipTime(3000);
            Logger.d("加载对话框一打开");
            //cameraKitView.captureImage(new CameraKitView.ImageCallback() {
                @Override
                public void onImage(CameraKitView cameraKitView, byte[] bytes) {
                    Logger.d("获取照片");
                    photoBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    Logger.d("照片大小："+photoBitmap.getByteCount());
                    WaitDialog.dismiss();
                    photoReturn(requestCode);
                }
            });*/
        //}
    }
    private void photoReturn(int requestCode){
        if(requestCode==RECY_TYPE_CARD){
            cardDialog.setTitle("扫码投递");
            cardDialog.show();
        }else if(requestCode==RECY_TYPE_QRCODE){
            cardDialog.setTitle("刷卡投递");
            cardDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode!=RECY_TYPE_PUBLIC_GOOD){
                if(requestCode==REG_FACE_CODE) {
                    int regStatus = data.getIntExtra("regStatus", -1);
                    if(REG_STATUS_CANCEL==regStatus){
                        return;
                    }
                    Bundle extras = data.getExtras();
                    byte photoBitmapByte[] = (byte[]) extras.get("photoData");
                    photoBitmap = BitmapFactory.decodeByteArray(photoBitmapByte,0,photoBitmapByte.length);
                    Logger.d("photo From data: "+photoBitmap);
                }else {
                    photoBitmap = (Bitmap) DataHelper.getInstance().getData("photoData");
                    Logger.d("photo From photoData:"+photoBitmap);
                }
            }
            if(requestCode==RECY_TYPE_CARD){
                cardDialog.setTitle("刷卡投递");
                cardDialog.show();
            }else if(requestCode==RECY_TYPE_QRCODE){
                cardDialog.setTitle("扫码投递");
                cardDialog.show();
               /* SharedPreferences deviceInfo = this.getSharedPreferences("device_info", MODE_PRIVATE);
                String qrcodeUrl = deviceInfo.getString("qrcodeUrl","");
                Logger.d("二维码："+qrcodeUrl);
                Bitmap content = ZXingUtils.createQRImage(qrcodeUrl, 400, 400);
                //qrcodeImageView.setImageBitmap(content);
                qrcodeImageView.setImageBitmap(content);
                qrcodeDialog.show();
                startScanOrder();*/
            }else if(requestCode==RECY_TYPE_PUBLIC_GOOD){
                photoBitmap  = (Bitmap)DataHelper.getInstance().getData("photoData");
                Logger.d("紧急按钮："+photoBitmap);
                msgDialog.setContent("正在打开回收箱门，请稍后。。。");
                msgDialog.show();
                Map<String,String> paramMap =new HashMap<>();
                Map<String, Object> binsTypeMap = binsDataList.get(binsType);
                Long wasteTypeId = (Long) binsTypeMap.get("id");

                paramMap.put("wasteTypeId",wasteTypeId+"");

               // loadingDialog.show();
                startScanOrder();

            }else if(requestCode==REG_FACE_CODE){
                faceReturn(data);
            }

            //RequestBody.create(bytes, MediaType.parse("image/png"));
        }else{
            alert("本次回收结束，感谢您的参与！");
        }
    }

    public void faceReturn(Intent data){
        int regStatus = data.getIntExtra("regStatus",-1);
        final String userLocalId = data.getStringExtra("userLocalId");
        this.faceLocalId = userLocalId;
        switch(regStatus){
            case REG_STATUS_REGING:
            case REG_STATUS_REGED:
                try {
                    UserInfo userInfo = null;
                    String userCardNo = data.getStringExtra("cardNo");
                    //showToast("服务器人脸信息：卡号："+userCardNo);
                    if(!StringUtils.isEmpty(userCardNo)) {
                        UserInfo userByCardNo = dbManager.selector(UserInfo.class).where("card_no", "=", userCardNo).findFirst();
                        if(userByCardNo==null){
                            //showToast("本地数据库不存在该卡号信息，创建新的信息！");
                            userInfo = UserInfo.builder().userId(data.getStringExtra("userId")).userName(data.getStringExtra("userName")).userNo(data.getStringExtra("userNo")).cardNo(userCardNo).photoName(userLocalId).build();
                            dbManager.save(userInfo);
                        }
                    }else{
                        userInfo =  dbManager.selector(UserInfo.class)
                                .where("photo_name", "=", userLocalId)
                                .findFirst();
                    }
                    //showToast("查询人脸数据库，用户信息："+userInfo);
                    if(userInfo!=null){
                        //showToast("本地数据库查询成功，跳转回收！");
                        /*Intent intent = new Intent(this,RecycleActivity.class);
                        intent.putExtra("userInfo",userInfo);
                        startActivity(intent);
                        MainActivity.this.loginMethod = LOGIN_QRCODE;*/

                        Map<String,String> paramMap =new HashMap<>();
                        Map<String, Object> binsTypeMap = binsDataList.get(binsType);
                        Long wasteTypeId = (Long) binsTypeMap.get("id");

                        paramMap.put("wasteTypeId",wasteTypeId+"");
                        String cardNo = userInfo.getCardNo();
                        Logger.d("人脸识别成功，卡号为："+cardNo);
                        paramMap.put("cardNo",cardNo);
                        paramMap.put("userNo",userInfo.getUserNo());

                        loadingDialog.show();
                        APIService.createOrder(paramMap, new DefaultCallback() {
                            public void response(String response,int code){
                                loadingDialog.dismiss();
                                ResponseData responseData1 = this.getResponseData(response);
                                if (responseData1.getSuccess()) {
                                    msgDialog.setContent("正在打开回收箱门，请稍后。。。");
                                    msgDialog.show();
                                    startScanOrder();
                                }else{
                                    showTip(responseData1.getMessage());
                                }
                                MainActivity.this.loginMethod = LOGIN_CARD;
                            }
                        });
                    }else{
                        //showToast("提交人脸图片到服务器！");
                        byte[] photoData = data.getByteArrayExtra("photoData");
                        faceData = photoData;
                        Logger.d("返回的人脸大小："+faceData.length);
                        byte[] faceFeatureBytes = data.getByteArrayExtra("featureData");
                        featureData = faceFeatureBytes;
                        if(featureData!=null){
                            Logger.d("返回的人脸特性大小："+featureData.length);
                        }else{
                            Logger.d("返回的人脸特性大小为空！");
                        }
                        {
                            MainActivity.this.loginMethod = LOGIN_FACE;
                            if(StringUtils.equals(bindType,"card")){
                                showToastCenter("\n请刷卡绑定人脸信息！\n",10);
                            }else
                            {//扫二维码绑定人脸
                                SharedPreferences deviceInfo = this.getSharedPreferences("device_info", MODE_PRIVATE);
                                String qrcodeUrl = deviceInfo.getString("qrcodeUrl", "");
                                Logger.d("二维码：" + qrcodeUrl);
                                Bitmap content = ZXingUtils.createQRImage(qrcodeUrl, 400, 400);
                                //qrcodeImageView.setImageBitmap(content);
                                qrcodeImageView.setImageBitmap(content);
                                qrcodeDialog.setTitle("请使用微信扫一扫扫码绑定人脸");
                                qrcodeDialog.show();
                                startScanOrder();
                            }
                            //提交服务器查询
                          /*  APIService.getUserByPhoto(photoData,new DefaultCallback(){
                                public void response(String response,int id){
                                    this.addLog("提交人脸图片返回："+response);
                                    ResponseData responseData = this.getResponseData(response);
                                    if(responseData.getSuccess()){
                                        com.alibaba.fastjson.JSONObject userInfoJson = (com.alibaba.fastjson.JSONObject)responseData.getData();
                                        if(userInfoJson!=null){
                                            UserInfo userInfo  = new UserInfo();
                                            //BeanUtil.copyProperties(userInfoJson,userInfo);
                                            Utils.copyProperties(userInfoJson,userInfo);
                                            userInfo.setPhotoName(userLocalId);
                                            try {
                                                Logger.d("人脸信息保存本地数据库："+JSON.toJSONString(userInfo));
                                                dbManager.save(userInfo);
                                            } catch (DbException e) {
                                                e.printStackTrace();
                                            }
                                            Intent intent = new Intent(MainActivity.this,RecycleActivity.class);
                                            intent.putExtra("userInfo",userInfo);
                                            startActivity(intent);
                                        }
                                        MainActivity.this.loginMethod = LOGIN_QRCODE;
                                    }else{
                                        MainActivity.this.loginMethod = LOGIN_FACE;
                                        showToastCenter("\n请刷二维码绑定人脸信息！\n",10);
                                    }
                                }
                            });*/
                        }
                    }

                } catch (DbException e) {
                    e.printStackTrace();
                }

        }
        //showToast(userLocalId);
    }
    ArrayList<Integer> scannedCodes = new ArrayList<Integer>();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Logger.d("二维码抢："+keyCodeToChar(keyCode,false));

        if(keyCode!= KeyEvent.KEYCODE_ENTER){ //扫码枪以回车为结束
            scannedCodes.add(keyCode);
            Logger.d("识别到二维码字符："+ keyCodeToChar(keyCode,false));
        }else { //结束

            //handleKeyCodes();


        }

        return super.onKeyDown(keyCode, event);
    }
    //扫码结束，返回值；刷卡人脸绑定
    private void handleKeyCodes(){
        String result = "";
        boolean hasShift = false;
        for(int keyCode : scannedCodes){
            result += keyCodeToChar(keyCode, hasShift);
            hasShift = (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT);
        }
        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        showToastCenter(result,10);
        scannedCodes.clear();
        final String cardNo = result;
        if(StrUtil.isNotBlank(cardNo)) {
            final Map<String,String> cardNoMap = new HashMap<>();
            cardNoMap.put("cardNo",cardNo);
            //showToast("刷卡卡号："+cardNo);
            if(this.loginMethod==LOGIN_CARD){
                //recycleByCard(cardNo);
                return;
            }
            UserInfo existUser = null;
            try {
                existUser = dbManager.selector(UserInfo.class).where("card_no", "=", cardNo).findFirst();
                if (existUser!=null) {
                    showTip("该卡号已被绑定！");
                    return;
                }
            } catch (DbException e) {
                e.printStackTrace();
            }

            APIService.cardNoSearch(cardNoMap, new DefaultCallback() {
                public void response(String response, int code) {

                    final ResponseData responseData = this.getResponseData(response);


                    if (responseData.getSuccess()) {
                        com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)responseData.getData();

                        User userInfo = new User();
                        userInfo.setUser_id(jsonObject.getString("user_id"));

                        recycleByCard(cardNo.toString(),userInfo);
                    } else {
                        //alert("身份验证信息", "您尚未关注公众号或小程序，请先关注再进行回收操作");

                        showTip("您尚未注册卡号，请先注册卡号！");
                    }
                }
            });
        }else{
            //showToast("二维码未识别到，请再");
        }
    }


    public void timerWeight(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Logger.d("获取远程命令列表。");
                APIService.hasCommandOrder(new DefaultCallback(){

                    @Override
                    public void response(String response, int id) {
                        //CommandFromService[] commandOrders = this.dataTo(CommandFromService[].class);
                        ResponseData responseData1 = this.getResponseData(response);
                        com.alibaba.fastjson.JSONArray commandOrders = (com.alibaba.fastjson.JSONArray)responseData1.getData();
                        if(commandOrders!=null) {
                            this.addLog("远程指令条数："+commandOrders.size());
                            UsbPortUtils usbPortUtils = new UsbPortUtils(MainActivity.this.port);
                            for (int i=0;i<commandOrders.size();i++) {
                                com.alibaba.fastjson.JSONObject commandOrder = commandOrders.getJSONObject(i);
                                CommandFromService commandFromService = commandOrder.getObject("commandObj",CommandFromService.class);
                                String key = commandOrder.getString("commandKey");
                                this.addLog("远程命令："+key);
                                CommandParam commandParam = CommandOrder.commandParamMap.get(key);
                                if(commandParam!=null){
                                    this.addLog("执行远程命令："+commandParam.getCommandName()+","+commandParam.getCommandVal());
                                    ResponseData responseData = usbPortUtils.sendForResult(commandParam);
                                    if(responseData!=null) {
                                        this.addLog("执行结果：" + responseData.getSuccess() + "," + responseData.getMessage() + "," + responseData.getData());
                                        commandFromService.setIsRead(responseData.getSuccess() ? 1 : 0);
                                        commandFromService.setIsFinish(responseData.getSuccess() ? 1 : 0);
                                        commandFromService.setReturnMsg((String) responseData.getData());
                                        APIService.updateCommandOrder(commandFromService, new DefaultCallback() {

                                        });
                                    }else{
                                        this.addLog("执行返回为空！");
                                    }
                                }else{
                                    this.addLog("没有找到对应的指令：");
                                }
                            }
                        }else{
                            this.addLog("没有发送远程命令。");
                        }
                    }
                });
            }
        },2000,30*1000);
    }
    public SharedPreferences getAppConfig(){
        SharedPreferences deviceInfoPreference = this.getSharedPreferences("device_info", Context.MODE_PRIVATE);
        return deviceInfoPreference;
    }
    public boolean isAdmin(String pwd){
        SharedPreferences appConfig = getAppConfig();
        String adminPwd = appConfig.getString("adminPwd", "");
        return false;
    }

    public void getLocationInfo(){

        mlocationClient.startLocation();

    }
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                int locationType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                double latitude = amapLocation.getLatitude();//获取纬度
                double longitude = amapLocation.getLongitude();//获取经度
                float accuracy = amapLocation.getAccuracy();//获取精度信息
                Logger.d("定位数据："+locationType+","+latitude+","+longitude+","+accuracy);
                mlocationClient.stopLocation();
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
                if(amapLocation.getErrorCode()==12){
                    XXPermissions.with(this)
                            .permission(Permission.ACCESS_COARSE_LOCATION)
                            .permission(Permission.ACCESS_FINE_LOCATION)
                            .request(new OnPermission() {
                                @Override
                                public void hasPermission(List<String> granted, boolean all) {
                                    if (all) {
                                        showToast("获取位置权限成功");
                                    } else {
                                        showToast("获取部分权限成功，但部分权限未正常授予");
                                    }
                                }
                                @Override
                                public void noPermission(List<String> denied, boolean never) {
                                    if (never) {
                                        showToast("被永久拒绝授权，请手动授予位置权限");
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        XXPermissions.startPermissionActivity(MainActivity.this, denied);
                                    } else {
                                        showToast("获取位置权限失败");
                                    }
                                }
                            });
                }
            }
        }
    }
    @Override
    public void onNetDisconnected() {
        Log.d("网络变化","网络断开");
        // ("网络断开");
    }

    @Override
    public void onNetConnected(NetworkType networkType) {
        Log.d("网络变化",networkType.toString());
        showToast("网络连接");
       /* Intent itent = new Intent();
        itent.setAction("com.arcsoft.arcface.activeserver");
        itent.setPackage("com.arcsoft.arcfacedemo");
        isFaceServiceActive = false;
        startService(itent);*/
        //Log.d("检查人脸激活状态","发送");
    }
    @Override
    protected void onResume() {
        super.onResume();
        //cameraKitView.onResume();
        NetStateChangeReceiver.registerObserver(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //cameraKitView.onStart();
    }
    @Override
    protected void onStop() {
        super.onStop();
        //cameraKitView.onStop();
    }
    @Override
    protected void onDestroy() {
        NetStateChangeReceiver.unregisterReceiver(this);
        unregisterReceiver(faceActiceReceiver);
        if(loadingDialog!=null){
            loadingDialog.dismiss();
        }
        super.onDestroy();
    }
    public class FaceActiceReceiver extends BroadcastReceiver {

        private final String TAG = "LocalReceiver";

        public FaceActiceReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isActive = intent.getBooleanExtra("isActive", false);
            Logger.d("激活状态返回："+isActive);
            WaitDialog.show(MainActivity.this,"人脸识别激活完毕").dismiss(1000);
            isFaceServiceActive = isActive;
        }

    }
    private byte[] startReadData(CommandParam commandParam) throws IOException {
        byte buffer[] = new byte[500];
        long beginTime = System.currentTimeMillis();
        int readLen =0;
        List<Byte> returnVals = new ArrayList<>();
        String orderFormRecycleLog = "";
        String portLog = "";
        portLog+="发送指令：《"+commandParam.getCommandName()+"，"+HexDump.toHexString(commandParam.getCommandVal())+"，读次数："+commandParam.getReadRepeat()+"，写次数："+commandParam.getWriteRepeat()+"》";
        orderFormRecycleLog+=portLog;
        int repeatMax = commandParam.getReadRepeat()<3?3:commandParam.getReadRepeat();
        for(int repeat=0;repeat<repeatMax;repeat++) {
            orderFormRecycleLog+=("【第"+(repeat+1)+"次读：");
            portLog+=("【第"+(repeat+1)+"次读：");
            do {
                readLen = port.read(buffer, commandParam.getReadTimeout());
                String readVal = null;

                if (readLen > 0) {
                    String temp = "";
                    for (int i = 0; i < readLen; i++) {
                        temp += HexDump.toHexString(buffer[i]) + "(" + new String(new byte[]{buffer[i]})+ ");";
                        orderFormRecycleLog+=( "《" + HexDump.toHexString(buffer[i]) + "（" + new String(new byte[]{buffer[i]}) + "）》");
                        returnVals.add(buffer[i]);
                    }

                    readVal = new String(buffer, 0, readLen);
                    portLog+="《"+temp+"》";
                }
                if(StrUtil.endWith(readVal,";")) break;
            } while (System.currentTimeMillis() - beginTime < commandParam.getReadTimeout());
            String endReadVal = "";
            if (returnVals.size() > 0) {
                readLen = returnVals.size();
                buffer = new byte[returnVals.size()];
                for (int i = 0; i < returnVals.size(); i++) {
                    buffer[i] = returnVals.get(i);
                }
                endReadVal = new String(buffer, 0, readLen);
                portLog+=("，最终读取结果：" + endReadVal+"】=> ");
            }else{
                portLog+="《空》】=> ";
            }
            orderFormRecycleLog+=( " ≡≡《" + endReadVal + "》" + "】");
            if(CommandParam.RETURN_FORCE==commandParam.getReturnType() && !StrUtil.endWith(endReadVal,";")){
                if(repeat>0 && commandParam.getWriteRepeat()+1-repeat>0){
                    int write = port.write(new byte[]{commandParam.getCommandVal()}, 400);
                    returnVals.clear();
                    continue;
                }
            }else{
                if("weight".equals(commandParam.getCommandTag())){
                    String number = endReadVal.replaceAll("[^0-9.]", "");
                    if (!NumberUtil.isDouble(number)) {
                        int write = port.write(new byte[]{commandParam.getCommandVal()}, 400);
                        returnVals.clear();
                        continue;
                    }
                }
                break;
            }
        }
        //Logger.d(TAG+"："+portLog);
        Logger.d(StrUtil.removeSuffix(portLog,"=> ")+"\n");

        return buffer;
    }
}
